import { AssetManager } from "cc";
import SystemBase from "./SystemBase";
import loader from "../util/loader";
import { resources } from "cc";
import { Sprite } from "cc";
import { Component } from "cc";
import { SpriteFrame } from "cc";
import { Asset } from "cc";


//加载指定包
export default class JLoaderBundle extends SystemBase{

    bundle:AssetManager.Bundle;
    bundleName:string;

    constructor(bundle:string){
        super();
        this.bundleName = bundle;
    }

    async onInit(): Promise<any> {
        if(this.bundleName == "resources"){
            this.bundle = resources;
            return;
        }
        this.bundle = await loader.getBundle(this.bundleName);
    }

    get(){
        return this.bundle;
    }
    
    load<T extends Asset>(res:string,onComplete?:((err: Error | null, data: T) => void)){
        this.get().load<T>(res,onComplete)
    }

    loadSpriteFrame(res:string,sprite:Sprite,comp:Component){
        
        this.load<SpriteFrame>(res,(err,data:SpriteFrame) => {

            if(!data) return;

            if(!sprite.isValid || !comp.isValid) {
                //提前销毁
                data.addRef();
                data.decRef();
            }
            
            sprite.spriteFrame = data;
            //添加引用标记
            data.addRef();

            //添加销毁资源引用
            let onDestroy = comp["onDestroy"];

            comp["onDestroy"] = () => {
                if(onDestroy)
                    onDestroy.bind(comp)();
                //销毁引用
                if(sprite.isValid && sprite.spriteFrame == data) sprite.spriteFrame = null;
                data.decRef();
            }

        })

    }


}

